<template>
  <div
    id="app"
    v-loading="loading.status"
    :element-loading-text="loading.txt"
    v-loading.fullscreen.lock="loading.full"
  >
    <router-view />
  </div>
</template>
<script>
import adapter from "webrtc-adapter";
import axios from "axios"; // 引入axios
export default {
  data() {
    return {
      pathOption: {
        personal: "", //个人中心跳转路径
        manage: "", //后台跳转路径
      },
      userInfo: {},
      longSocket: null,
      loading: {
        status: false,
        txt: "正在退出系统...",
        full: false,
      },
      initFlag: true,
    };
  },
  created() {
    this.get_access_token();
    this.checkLogin();
    if (this.initFlag) {
      this.checkIsMultilevel();
      this.checkIsSchool();
      this.initFlag = false;
    }
    this.checkIsGray();
    //下面2方法在tools/common.js中
    this.getLogo();
    this.getTitle();
  },
  mounted() {
    this.getWebrtcFlag();

    if (sessionStorage.getItem("store")) {
      this.$store.replaceState(
        Object.assign(
          {},
          this.$store.state,
          JSON.parse(sessionStorage.getItem("store"))
        )
      );
      sessionStorage.removeItem("store");
    }
    //在页面刷新时将vuex里的信息保存到sessionStorage里
    window.addEventListener("beforeunload", () => {
      sessionStorage.setItem("store", JSON.stringify(this.$store.state));
    });
  },
  watch: {
    isoutlogin(newVal, oldVal) {
      if (newVal) {
        this.loginOut();
        if (this.longSocket) {
          let params = {
            type: "login_out",
            token: sessionStorage.getItem("token"),
            terminal_type: 1,
          };
          this.longSocket.send(JSON.stringify(params));
        }
      }
    },
  },
  computed: {
    isoutlogin() {
      return this.$store.getters.outlogin;
    },
  },
  methods: {
    myBrowser() {
      //取得浏览器的userAgent字符串
      let userAgent = navigator.userAgent;
      // 如果不是谷歌浏览器则返回false 
      if(userAgent.indexOf('Chrome') == -1) return false
      // 获取Chrome浏览器的版本
      let num = userAgent.toLowerCase().match(/chrome\/([\d.]+)/)[1].split('.')[0]
      //判断Chrome浏览器 85版本以上可用
      let isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1 && num > 85; 
      return isChrome;
    },

    getWebrtcFlag() {
      let adapter_test = adapter.browserDetails.browser;
      //检查是否允许webrtc
      if (adapter_test !== "Not a supported browser.") {
        this.$store.commit("SET_WEBRTCFLAG", true);

        //判断是否允许开九个画面
        if (this.myBrowser()) {
          this.$store.commit("SET_ALLOWNINEFLAG", true);
        }
      }
      // 4.0 webrtc前版本
      this.$store.commit("SET_WEBRTCFLAG", false);
      this.$store.commit("SET_ALLOWNINEFLAG", false);
    },
    //注释
    //查看是否是多级
    checkIsMultilevel() {
      let success = (res) => {
        const flag = res.data === 2;
        this.$store.commit("SET_MULTI", flag);
      };
      this.$ajax({
        url: "appapi/login/check_level_platform",
        method: "get",
        params: {},
        func: {
          success: success,
        },
      });
    },
    //查看当前平台是学校还是教育局
    checkIsSchool() {
      let success = (res) => {
        const flag = res.data === 1;
        this.$store.commit("SET_SCHOOL", flag);
      };
      this.$ajax({
        url: "api/newlevel/check_platform_server_type",
        method: "get",
        params: {},
        func: {
          success: success,
        },
      });
    },
    get_access_token() {
      axios.get("/accessToken", {
          params: {
            company: "BL",
            device_name: "TE-0600R",
            data: {
              client_id: this.$g.client_id,
              secret: this.$g.secret,
            },
          },
        })
        .then((response) => {
          let data = response.data.data;
          this.$g.access_token = data.access_token;
          localStorage.setItem("access_token", data.access_token);
        });
    },
    //查看页面是否置灰
    checkIsGray() {
      let success = (res) => {
        if (res.data.status) {
          document.getElementsByTagName("body")[0].classList.add("is-gray");
        } else {
          document.getElementsByTagName("body")[0].classList.remove("is-gray");
        }
      };
      this.$ajax({
        url: "api/setting/gray",
        method: "get",
        params: {},
        func: {
          success: success,
        },
      });
    },
    //登录信息
    checkLogin() {
      let success = (data) => {
        this.userInfo = data.data.userinfo;
        this.getBaseUrl();
        this.globalMessage(); //WebSocket获取全局信息提示
        this.websocketInit();
        sessionStorage.setItem(
          "user_info_str",
          JSON.stringify(deep_clone(data.data.userinfo))
        );
      };
      let fail = (data) => {};
      this.$ajax({
        url: "api/login/login",
        method: "get",
        headers: {'token': localStorage.getItem('loginToken')},
        params: {},
        func: {
          success: success,
          fail: fail,
        },
      });
    },
    // 获取跳转路径（个人中心，后台）
    getBaseUrl() {
      let protocol = sessionStorage.getItem("protocol");
      let host = sessionStorage.getItem("host");
      let token = sessionStorage.getItem("token");
      if (token != "--") {
        this.pathOption.personal = `${protocol}://${host}/personal/login?token=${token}&protocol=${protocol}&host=${host}`;
        this.pathOption.manage = `${protocol}://${host}/admin/login?token=${token}&protocol=${protocol}&host=${host}`;
      } else {
        this.pathOption.personal = `${protocol}://${host}/personal/?protocol=${protocol}&host=${host}`;
        this.pathOption.manage = `${protocol}://${host}/admin/?protocol=${protocol}&host=${host}`;
      }
    },
    //添加已读记录
    addReadRecord(type, id) {
      let success = (data) => {};
      this.$ajax({
        url: "api/message/set_read",
        method: "post",
        data: {
          type: type,
          id: id,
        },
        func: {
          success: success,
        },
      });
    },
    //全局消息
    globalMessage() {
      //是否登录
      if (this.userInfo.id == 0) {
        return;
      }
      //登录连接后台socket接收消息
      let webSocketURL = "ws:" + this.BASE_URL.split(":")[1] + ":7575";
      var ws = new WebSocket(webSocketURL);
      ws.onopen = () => {
        var message = JSON.stringify({
          type: "login",
          user_id: this.userInfo.id,
        });
        ws.send(message);
      };
      ws.onmessage = (evt) => {
        var data = JSON.parse(evt.data);
        let that = this;
        that.$notify({
          title: "【" + data.content_type + "】",
          message: data.title,
          customClass: "globelMessageDialog",
          duration: 3000,
          offset: 130,
          //全局信息点击事件
          onClick: function () {
            that.globalMessageType = data.global_message_type;
            if (
              data.global_message_type == "notice" ||
              data.global_message_type == "comment"
            ) {
              that.globalNoticeMessageCheckLook(
                data.id,
                data.type,
                data.template,
                data.content_id,
                data.module
              );
            }
            that.addReadRecord(data.type, data.id);
          },
        });
      };
      ws.onclose = function () {
        // 关闭 websocket
      };
    },
    /**全局消息通知查看转发
     * @param id 自增id
     * @param type 消息内容类型（1：消息；2：班级通知；3：动态；4：收到的评论；5：发起的評論）
     * @param template 模板对应index  0:不使用模板
     * @param contentId 内容id
     * @param moduleVal 所属模块
     */
    globalNoticeMessageCheckLook(id, type, template, contentId, moduleVal) {
      if (parseInt(type) == 1) {
        this.noticeCheckLook(template, contentId, moduleVal);
      } else if (parseInt(type) === 2) {
        this.followCheckLook(template, contentId, moduleVal);
      } else if (parseInt(type) === 3) {
        this.groupCheckLook(template, contentId, moduleVal);
      } else if (parseInt(type) === 4) {
        this.globalCommentMessageCheckLook(contentId, moduleVal);
      }
    },
    // 跳个人中心相关的模块
    linkToPresonalModule(moduleUrl) {
      let protocol = sessionStorage.getItem("protocol");
      let host = sessionStorage.getItem("host");
      let token = sessionStorage.getItem("token");
      let urlString = `/personal/login?token=${token}&protocol=${protocol}&host=${host}&routerUrl=${moduleUrl}`
      // let urlString = this.pathOption.personal + "&routerUrl=" + moduleUrl;
      window.open(urlString, "_blank");
    },
    //全局消息通知跳转
    noticeCheckLook(template, contentId, moduleVal) {
      // console.log(template, contentId, moduleVal)
      //班级通知->个人中心班级通知
      if (template === "0" && moduleVal == "class") {
        this.linkToPresonalModule("notice");
      }
      //请假->个人中心请假
      else if (moduleVal == "leave") {
        this.linkToPresonalModule("leave");
      }
      //班级任务->个人中心班级任务
      else if (moduleVal == "task") {
        this.linkToPresonalModule("homework");
      }
      //直播
      else if (moduleVal == "live") {
        let success = (res) => {
          if (data.data.role_id.indexOf(1) > -1) {
            this.linkToPresonalModule("/teach/live/listlive");
          } else {
            this.$router.push({
              path: "/home/liveRoom",
              query: { id: contentId },
            });
          }
        };
        this.$ajax({
          url: "/api/user/user_info",
          method: "get",
          params: {
            id: this.userInfo.id,
            level: 2,
          },
          func: { success: success },
        });
      }
      //问答
      else if (moduleVal == "question") {
        if (template === "question_1") {
          this.linkToPresonalModule("/teach/ask/index");
        } else if (template === "question_2") {
          this.$router.push({
            path: "/home/openclassDetail",
            query: { id: contentId },
          });
        }
      }
      //备课
      else if (moduleVal == "prepare") {
        this.$router.push({
          path: "/prepare/edit",
          query: { id: contentId },
        });
      }
      //跳去邮件
      else if (moduleVal == "email") {
        this.$router.push({ path: "/email/inbox#id=" + contentId });
      }
    },
    //全局消息关注跳转
    followCheckLook(template, contentId, moduleVal) {
      if (moduleVal == "resource") {
        this.$router.push({
          path: "/home/resourceDetail",
          query: { id: contentId },
        });
      } else if (moduleVal == "live") {
        this.$router.push({
          path: "/home/liveRoom",
          query: { id: contentId },
        });
      } else if (moduleVal == "video") {
        this.$router.push({
          path: "/home/openclassDetail",
          query: { id: contentId },
        });
      }
    },
    //全局消息圈组跳转
    groupCheckLook(template, contentId, moduleVal) {
      if (
        template == "group_0" ||
        template == "group_1" ||
        template == "group_3"
      ) {
        this.$router.push({
          path: "/group/introduct",
          query: { id: contentId },
        });
      } else if (template == "group_4" || template == "group_2") {
        this.$router.push("/group/manage/selfCreated");
      }
    },
    //全局消息评论跳转
    globalCommentMessageCheckLook(contentId, moduleVal) {
      //公开课评论跳转
      if (moduleVal == "video") {
        this.$router.push({
          path: "/home/openclassDetail",
          query: { id: contentId },
        });
      }
      // //资源评论跳转
      else if (moduleVal == "resource") {
        this.$router.push({
          path: "/home/resourceDetail",
          query: { id: contentId },
        });
      }
    },
    websocketInit() {
      if (this.userInfo.id == 0) {
        return;
      }
      let webSocketURL = "ws:" + this.BASE_URL.split(":")[1] + ":7474";
      this.longSocket = new WebSocket(webSocketURL);

      this.longSocket.onopen = (res) => {
        let params = {
          type: "login",
          token: sessionStorage.getItem("token"),
          terminal_type: 1,
        };

        this.longSocket.send(JSON.stringify(params));
      };

      this.longSocket.onmessage = (res) => {
        let type = JSON.parse(res.data).type;

        switch (type) {
          case "outlogin":
            this.$message.error("该账号已被其他用户登录");
            setTimeout(() => {
              this.loginOut();
            }, 1000);
            break;
          // case 'outlogin_one':
          //     !this.$store.getters.outlogin && this.$message.error('其他用户已退出该账号');
          //     this.loginOut();
          //     break;
          case "delete_outlogin":
            this.$message.error("用户发送变化，请重新登录");
            setTimeout(() => {
              this.loginOut();
            }, 1000);
            break;
          default:
            break;
        }
      };

      this.longSocket.onclose = (res) => {};
    },
    // //退出账号
    loginOut() {
      // this.$store.commit('SET_OUTLOGIN', false);
      // sessionStorage.clear();
      // localStorage.clear();
      // window.location.href = window.location.origin + '/cas/logout';//军哥要求的版本单点登录退出版本

      let that = this;
      that.loading.txt = "正在退出系统...";
      that.loading.full = true;

      this.$store.commit("SET_OUTLOGIN", false);

      if (JSON.parse(sessionStorage.getItem("user_info_str")).logout_url) {
        that.loading.txt = "退出成功...";
        that.loading.full = false;
        let user_info_str = JSON.parse(sessionStorage.getItem("user_info_str"));
        setTimeout(() => {
          sessionStorage.clear();
          localStorage.clear();
          this.$store.commit("SET_USERINFO", {});
          window.location.href = user_info_str.logout_url;
        }, 800);
      } else {
        let success = (data) => {
          that.loading.txt = "退出成功...";
          that.loading.full = false;
          let host_addr = sessionStorage.getItem("host_addr");
          sessionStorage.clear();
          localStorage.clear();
          this.$store.commit("SET_USERINFO", {});
          window.location.href = host_addr;
        };
        let fail = (data) => {
          that.$message.error(data.msg);
          that.loading.txt = data.msg;
          that.loading.full = false;
          that.loading.status = false;
        };

        that.$ajax.delete("api/login/login", { func: { success, fail } });
      }
    },
  },
};
</script>
<style lang="scss">
body,
html {
  background: #eafaff;
}
.is-gray {
  -webkit-filter: grayscale(100%);
  -moz-filter: grayscale(100%);
  -ms-filter: grayscale(100%);
  -o-filter: grayscale(100%);
  filter: grayscale(100%);
  filter: gray;
}
.i_copyright {
  white-space: pre;
}
.globelMessageDialog.el-notification.right {
  width: 300px;
  height: 64px;
  cursor: pointer;
  .el-notification__title {
    font-size: 14px;
    color: #d49b07;
  }
  .el-notification__group {
    margin-left: 0;
  }
  .el-notification__content p {
    width: 255px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .el-notification__closeBtn {
    top: 8px;
    right: 8px;
    padding: 2px;
    color: #fff;
    background-color: #0749aa;
    border-radius: 50%;
  }
}
/* 日期控件的 此刻按钮 */
.el-picker-panel__footer {
  .el-button--text {
    display: none;
  }
}
</style>


